<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <input type="text" id="uid" placeholder="请输入你的id"/><br>
    <button onclick="onConnectionClick();">连接服务器</button><span id="connectionInfo"></span><br>
    <div id="msgs"></div>


<script>
    let socket;
    function onConnectionClick(){
        if(typeof(WebSocket)=="undefined"){
            //浏览器不支持websocket
            document.getElementById("connectionInfo").innerHTML="浏览器不支持WebSocket";
        }else{
            if(socket!=null){
                socket.close();
                socket=null;
            }
            //获取用户的id
            let uid=document.getElementById("uid").value;
            //给服务器说明自己是谁，需要携带参数
            //这里不再是以http开头，因为使用的协议已经变为websocket
            let url="ws://localhost:9005/webSocket/"+uid;
            //websocket实例化
            socket=new WebSocket(url);

            socket.onopen=function(){
                document.getElementById("connectionInfo").innerHTML="已经与服务器建立连接";
            };
            socket.onmessage=function(msg){
                let receiveMessage=msg.data;
                document.getElementById("msgs").innerHTML="<span>"+receiveMessage+"</span><br>";
            };
            socket.onclose=function(){
                document.getElementById("connectionInfo").innerHTML="连接已经关闭";
            };
            socket.onerror=function(){
                document.getElementById("connectionInfo").innerHTML="连接出现异常";
            };
        }
    }
</script>
</body>
</html>